package com.gxa.luckin.order.controller;

import com.gxa.luckin.core.exception.BusinessException;
import com.gxa.luckin.core.result.Result;
import com.gxa.luckin.order.dto.OrderDTO;
import com.gxa.luckin.order.pojo.Order;
import com.gxa.luckin.order.pojo.OrderItem;
import com.gxa.luckin.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.net.URISyntaxException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: XHZ
 * @date: 16:17 2021/7/16
 */
@RestController
@Slf4j
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    //1.下单
    @PostMapping("/create")
    public Result create(@RequestBody OrderDTO orderDTO, BindingResult bindingResult, Integer shopId, Long userId) throws BusinessException, URISyntaxException {
        if (bindingResult.hasErrors()) {
            List<String> errors =
                    bindingResult.getAllErrors().stream()
                            .map(ObjectError::getDefaultMessage).
                            collect(Collectors.toList());
            log.error("创建订单参数不正确, orderDTO={}", orderDTO);
            return new Result(5000, "参数不正确");
        }
        String orderId = orderService.createOrder(userId, orderDTO, shopId);
        return new Result(orderId);
    }

    @PostMapping("/query")
    public Result queryOrder(@RequestParam String orderId) {
        Order order = orderService.queryOrderById(orderId);
        return new Result(order);
    }

    @PostMapping("/queryAll")
    public Result queryAllByUserId(@RequestParam Long userId) {
        List<Order> orderList = orderService.queryAllByUserId(userId);
        return new Result(orderList);
    }

    @PostMapping("/queryOrderItem")
    public Result queryOrderItemByOrderId(@RequestParam String orderId) {
        List<OrderItem> orderItems = orderService.queryOrderItemByOrderId(orderId);
        return new Result(orderItems);
    }

}
